
// CREATE BUY CARDS ACCORDION

$( function() {

	var buyCardsAccordion = $("#buy-cards-accordion");
	for ( var i = 0; i < CIVILIZATIONS_ORDER.length; i++) {
		var civ = CIVILIZATIONS_ORDER[i];
		var civInfo = getCivilizationInformation(civ);
		var civDiv = $('<h3 style="display: none"><a class="' + civ
				+ '" href="#" id="buy-' + civ + '-title">' + civInfo.name
				+ '</a></h3><div style="display: none" id="buy-' + civ
				+ '"></div>');
		buyCardsAccordion.append(civDiv);
	}

	buyCardsAccordion.accordion( {
		collapsible :true,
		active :false,
		autoHeight :false,
		animated :false
	});

});

// CREATE BUY CARDS CONTAINER

$( function() {

	var buyCardsContainer = $("#buy-cards-container");

	for ( var i = 0; i < CIVILIZATION_CARDS_ORDER.length; i++) {
		var cardid = CIVILIZATION_CARDS_ORDER[i];
		var card = getCivilizationCardInformation(cardid);

		var cs = getCivilizationCardGroups(cardid);
		var groupIcons = "";
		for ( var k = 0; k < cs.length; k++) {
			groupIcons = groupIcons + '<span style="padding-left:15px" class="'
					+ cs[k] + '"></span>';
		}

		var cardDiv = $('<div><table id="cardid-container-'
				+ cardid
				+ '" class="civilization-card-table"><tr class="civilization-card"><td class="civilization-card-checkbox"><input class="buy-card-button" type="checkbox" name="cardid-'
				+ cardid + '" id="cardid-' + cardid
				+ '" /></td><td class="civilization-card-icons">' + groupIcons
				+ '</td><td class="civilization-card-title">' + card.name
				+ '</td><td class="civilization-card-value" id="cardvalue-'
				+ cardid
				+ '"></td><td class="civilization-card-value" id="cardprice-'
				+ cardid + '"></td></tr></table></div>');

		buyCardsContainer.append(cardDiv);

	}

	buyCardsContainer.sortable( {
		distance :15
	});
	buyCardsContainer.disableSelection();

});

// NETWORK CONNECTION BUTTON
$( function() {
	var connectButton = $("button#connect-button").button();
	connectButton.click( function() {
		connectionButtonPressed();
	});

	setConnectionStatus(null);
});

// CREATE MANAGE CIVILIZATIONS ACCORDION
$( function() {

	var manageCivilizationsAccordion = $("#manage-civilizations-accordion");
	for ( var i = 0; i < CIVILIZATIONS_ORDER.length; i++) {
		var civ = CIVILIZATIONS_ORDER[i];
		var civInfo = getCivilizationInformation(civ);
		var civDiv = $('<h3><a class="' + civ
				+ '-disabled" href="#" id="manage-' + civ + '-title">'
				+ civInfo.name
				+ '</a></h3><div style="display: none" id="manage-' + civ
				+ '"></div>');
		manageCivilizationsAccordion.append(civDiv);
	}

	manageCivilizationsAccordion.accordion( {
		collapsible :true,
		active :false,
		autoHeight :false,
		animated :false
	});

});

// AJAX SETUP

$( function() {
	$.ajaxSetup( {
		global :true,
		type :"POST",
		timeout :20000,
		dataType :"json",
		contentType :"application/json",
		statusCode : {
			404 : function() {
				openMessageDialog("404: not found");
				setConnectionStatus(null);
			},
			503 : function() {
				openMessageDialog('Internal server error');
				setConnectionStatus(null);
			}
		},
		error : function(req, msg) {
			openMessageDialog("Network connection error: " + msg);
			setConnectionStatus(null);
		}

	});
});

$( function() {
	$("div#progress-field").ajaxStop( function() {
		$(this).hide();
	});
});

$( function() {
	$("div#progress-field").ajaxStart( function() {
		$(this).show();
	});
});

// NETWORK DIALOG and MESSAGE DIALOG

$( function() {
	var dialog = $('div#network-dialog').dialog( {

		position :'center',
		autoOpen :false,
		buttons : {
			"Connect" : function() {
				connectToServer();
			},
			"Cancel" : function() {
				closeNetworkDialog();
			}

		},
		modal :true,
		width :460,
		minWidth :460,
		height :300,
		minHeight :300

	});

	dialog.find(":input").each( function(i) {
		$(this).keypress( function(event) {
			if (event.which == '13') {
				event.preventDefault();
				connectToServer();
			}
		});
	});

});

$( function() {

	$("div#message-dialog").dialog( {
		modal :true,
		position :"center",
		autoOpen :false,
		buttons : {
			Ok : function() {
				$(this).dialog("close");
			}
		}
	});
});

function connectionButtonPressed() {
	if (sessionId == null) {
		openNetworkDialog();
	} else {
		openMessageDialog("Disconnected: " + sessionId);
		setConnectionStatus(null);
	}
}

function openNetworkDialog() {
	var dialog = $("div#network-dialog");
	var connectionStatusField = dialog.find("#connection-status-text");
	connectionStatusField.text("");

	dialog.dialog("open");

}

function closeNetworkDialog() {
	$("div#network-dialog").dialog("close");

}

function openMessageDialog(message) {
	var dialog = $("div#message-dialog");
	var messageField = dialog.find("#message-text");
	messageField.text(message);

	dialog.dialog("open");

}

var sessionId = null;

function setConnectionStatus(sid) {
	sessionId = sid;
	var connectButton = $("button#connect-button").button();
	if (sessionId == null) {
		connectButton.text("Login...");
		setSessionCreatedDate(null);
	} else {
		connectButton.text("Logout: " + sessionId);
	}
}

function setSessionCreatedDate(date) {
	var d = $("div#session-created-date");
	if (date==null) {
		d.empty();
	}
	else {
		d.html(formatDateTime(date));
	}
}

function connectToServer() {

	var d = $("div#network-dialog");
	var idInput = d.find("input#game-id");
	var id = idInput.val();
	id = $.trim(id);
	idInput.val(id);
	if (id == "") {
		idInput.focus(10);
		return;
	}

	var password = d.find("input#game-password")[0].value;
	var connectionStatusField = d.find("#connection-status-text");
	connectionStatusField.text("Connecting...");

	$.ajax( {
		url :"civaid/connect?id=" + id,
		data :$.JSON.encode(password),
		success : function(msg) {
			if (msg.status == "JOINED") {
				connectionStatusField.text("Joined to session");
				setConnectionStatus(id);
				setSessionCreatedDate(new Date(msg.created));

				var callback = function() {
					updateSelectedUI(selectedTab);
					closeNetworkDialog();
				}
				doSessionSynchronization(callback);

			} else if (msg.status == "CREATED") {
				connectionStatusField.text("Created new session");
				setConnectionStatus(id);
				setSessionCreatedDate(new Date(msg.created));

				var callback = function() {
					closeNetworkDialog();
				}
				doSessionSynchronization(callback);

			} else if (msg.status == "AUTHENTICATION_FAILED") {
				connectionStatusField.text("Authentication failed");
			} else {
				connectionStatusField.text("Unknown error");
				openMessageDialog(msg);
			}
		}
	});
}

// $(window).bind('beforeunload', function() { return 'Do you really want to
// leave?' ; });

